const express = require('express')
const url = require('url')
const fs = require('fs')

const app = new express();
/**
 * 中间件：middle ware
 * request ---> middle ware ---> router ---> response ---> client
 */
/**
 * 创建中间件，记录访问者的url
 * 把url 写入一个文本文件
 */
const logger = (req,res,next)=>{
    console.log("logging")

    const urlObject = url.parse(req.url,true)
    console.log("%s is request a router",urlObject.pathname)

    let message = urlObject.pathname+" is request a router "
    fs.writeFile('log.txt', message, function (err) {
        if (err) {
            console.log(err);
        }
    })

    res.write('middle ware')
    next()
}

app.use(logger)

app.get('/',(req,res)=>{
    res.end(' --> router')
})

const server = app.listen(3000,'localhost',(req,res)=>{
    const address = server.address();
    console.log(" This is http://%s:%s",address.address,address.port)
})
